package lazy.libs.utils;

import java.util.ArrayList;

import lazy.model.Post;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class HTMLUtil {

	/**
	 * 解析html
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static Document repair(String url) throws Exception {
		String content = HtmlFileUtil.downloadAsStringBuffer(url).toString();
		return Jsoup.parse(content);
	}

	/**
	 * 查找
	 * 
	 * @param doc
	 * @param classOfCSS
	 * @return
	 */
	public static Elements findByClass(Document doc, String classOfCSS) {
		// 根据class查找
		Elements elements = doc.getElementsByClass(classOfCSS);
		return elements;
	}

	// String url = "http://www.xiankankan.com/index.php/page/2";

	public static void main(String[] args) throws Exception {
		String url = "http://www.007ka.cn/partnernew/";
		url = "http://www.xiankankan.com/index.php/page/2";
		String classOfCSS = "content";
		Document doc = repair(url);
		Elements elements = findByClass(doc, classOfCSS);
		int i = 0;
		for (Element element : elements) {
			i++;
			// if (i < 4)
			// continue;

			Post post = new Post();

			System.out.println("--");
			System.out.println("--html--");
			System.out.println("html:" + element.toString());

			post.html = element.toString();

			Elements es2 = element.select("a.more-link");
			for (Element e : es2) {
				System.out.println("href--->" + e.attr("href"));

				post.url = e.attr("href");

				Element e2 = e.parent().select("p").first();
				System.out.println("txt--->" + e2.ownText());

				post.txt = e2.ownText();
			}
			// es3
			// <img class="alignnone size-full wp-image-25493" title="75c63b6b910b45cec77df7d5973e092a_large"
			// src="http://www.xiankankan.com/wp-content/uploads/2013/04/75c63b6b910b45cec77df7d5973e092a_large.jpg"
			// alt="" width="500" height="334" />
			Elements es3 = element.select("img[src]");
			if (es3.first() != null) {
				System.out.println("img--->" + es3.first().attr("src"));
				post.img = es3.first().attr("src");
			}

			if (post.notNull()) {
				postList.add(post);
			}
		}

		for (Post p : postList) {
			System.out.println("======== post =========");
			System.out.println("txt -->" + p.txt);
			System.out.println("url -->" + p.url);
			System.out.println("img -->" + p.img);
		}
	}

	public static ArrayList<Post> postList = new ArrayList<Post>();

}
